package net.xdclass.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.mq.RedisMqSmsSendConsumer;
import net.xdclass.mq.RedisMqSmsSendMessage;
import net.xdclass.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Tag(name = "通知模块")
@RestController
@RequestMapping("/api/user/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private RedisMqSmsSendConsumer redisMqSmsSendConsumer;
    private static final long CAPTCHA_EXPIRATION = 60 * 1000 *10;
    @Operation(summary="获取图形验证码")
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {

//        RedisMqSmsSendMessage message = new RedisMqSmsSendMessage().setLogId(1L);
//        redisMqSmsSendConsumer.onMessage(new ObjectRecord());

        String captchaText = captchaProducer.createText();
        log.info("图形验证码:{}",captchaText);

        //存储
        redisTemplate.opsForValue().set(getCaptchaKey(request),captchaText,CAPTCHA_EXPIRATION, TimeUnit.MILLISECONDS);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
            outputStream.flush();
            outputStream.close();
        }catch (IOException e){
            log.error("获取图形验证码失败",e);
        }
    }

    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "user-service:captcha" + CommonUtil.MD5(ip + userAgent);
        log.info("ip={}",ip);
        log.info("userAgent={}",userAgent);
        log.info("key={}",key);
        return key;
    }
}
